from django.contrib.auth.decorators import user_passes_test
from django.conf import settings

from accounts.models import *

def is_account_user(user, account=None):
	"""
	Returns True if the specified auth.User has an associated
	AccountUser instance for the Acccount.
	If `account` is None, the current Account (if available) is used.
	"""
	if not user.is_authenticated():
		return False
	if user.is_superuser and getattr(settings, 'ALLOW_SUPERUSER_LOGIN', True):
		return True
	if account is None:
		account = Account.objects.get_current()
	if account:
		try:
			AccountUser.objects.get(user=user, account=account)
			return True
		except AccountUser.DoesNotExist:
			return False
	return False
			

def is_account_owner(user, account=None):
	"""
	Returns True if the specified auth.User is the Account.auth_owner
	If 'account' is None, the current Account (if available) is used.
	Also returns True if the auth.User.is_superuser and ALLOW_SUPERUSER_LOGIN
	is True (default).
	"""
	if not user.is_authenticated():
		return False
	if user.is_superuser and getattr(settings, 'ALLOW_SUPERUSER_LOGIN', True):
		return True
	if account is None:
		account = Account.objects.get_current()
	if account:
		return account.auth_owner == user
	else:
		return None
		
def account_login_required(func):
	"View decorator that requires an authenticated AccountUser."
	return user_passes_test(is_account_user, login_url=settings.LOGIN_URL)(func)
	
def account_owner_required(func):
	"View decorator that requires user to be the Account owner."
	return user_passes_test(is_account_owner, login_url=settings.LOGIN_URL)(func)